package com.zqs.grainmall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.zqs.common.constant.AuthServerConstant;
import com.zqs.common.exception.BizCodeEnums;
import com.zqs.common.utils.Constant;
import com.zqs.common.utils.R;
import com.zqs.common.vo.MemberResponseVo;
import com.zqs.grainmall.auth.feign.MemberFeignService;
import com.zqs.grainmall.auth.feign.ThirdPartFeignService;
import com.zqs.grainmall.auth.vo.UserLoginVo;
import com.zqs.grainmall.auth.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @program: grain-mall
 * @description:
 * @author: Mr.Zhang
 * @create: 2020-11-16 19:07
 **/
@Controller
public class LoginController {
    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone){

        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        //防止同一个手机号在60秒内再次发送验证码
        if (!StringUtils.isEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                //60秒内不能再发
                return R.error(BizCodeEnums.SMS_CODE_EXCEPTION.getCode(), BizCodeEnums.SMS_CODE_EXCEPTION.getMsg());
            }
        }


        //1.接口防刷
        //2.验证码的再次校验。redis,寸key-phone value-code  sms:code:17683934xxx->45678
        String code=UUID.randomUUID().toString().substring(0,5);
        String substring= code+"_"+System.currentTimeMillis();

        //10分钟有效
        //redis缓存验证码，防止同一个手机号在60秒内再次发送验证码
       stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,substring,10, TimeUnit.MINUTES);

       thirdPartFeignService.sendCode(phone,code);

        return R.ok();

    }

    /**
     *  //TODO 重定向携带数据，利用session原理，将数据放在session中。只要跳到下一个页面取出这个数据后，session里面的数据就会删掉
     *  //TODO 分布式session的问题
     * 如果我们用了Model的话，重定向后不能获取mode里面的数据，所以:
     *  使用RedirectAttributes redirectAttribute 重定向携带数据
     * */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result,
                         RedirectAttributes redirectAttributes){
        if (result.hasErrors())
        {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);
            //TODO error: Request method 'POST' not supported
            //用户注册-》/regist[post]-->转发/reg.html(路径映射默认都是get方式访问的)，所以不能使用forward
            //校验出错
            //return "forward:/reg.html";
            return "redirect:http://127.0.0.1:20000/reg.html";

        }

        //真正注册，调用远程服务进行注册
        //1.校验验证码
        String code = vo.getCode();
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if(!StringUtils.isEmpty(s))
        {
            if (code.equals(s.split("_")[0])) {
                //通过后删除验证码,令牌机制
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+vo.getPhone());
                //验证码通过,真正注册。调用远程注册
                R r = memberFeignService.regist(vo);
                if (r.getCode()==0)
                {
                    //注册成功回到首页,回到登陆页
                    return  "redirect:http://127.0.0.1:20000/login.html";
                }else
                {
                    Map<String,String> errors=new HashMap<>();
                    errors.put("meg",r.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);

                   return  "redirect:http://127.0.0.1:20000/reg.html";
                }


            }
            else {
                Map<String,String> errors=new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://127.0.0.1:20000/reg.html";

            }

        }else
        {
            Map<String,String> errors=new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            //校验出错，重定向到注册页
            return "redirect:http://127.0.0.1:20000/reg.html";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        //远程登陆
        R login = memberFeignService.login(vo);
        if (login.getCode()==0)
        {
            //成功
            MemberResponseVo data = login.getData("data", new TypeReference<MemberResponseVo>() {});
            //放到session中
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            System.out.println("登陆成功");
           return  "redirect:http://127.0.0.1:10000";
        }else {
            //失败
            HashMap<String, String> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://127.0.0.1:20000/login.html";
        }



    }


    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute==null)
        {
            //没登陆
            return "login";

        }
        else
        {
            return "redirect:http://127.0.0.1:10000";
        }


    }

}
